package mock;

import mock.entity.Person;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.Collections;
import java.util.Set;

/**
 *
 * @author vladimirs 05.09.2013   12:18
 */
public class DataProvider {

    protected final Log logger = LogFactory.getLog(getClass());

    String xmlPath = "web/store/content.xml";
    final File xmlFile = new File(xmlPath);

    public Set<Person> getData() {
        ApplicationContext context = ApplicationContextProvider.getApplicationContext();
        Unmarshaller unMarshaller = (Unmarshaller) context.getBean("xstreamMarshallerBean");
        synchronized (xmlFile) {
            try {
                return (Set<Person>) unMarshaller.unmarshal(new StreamSource(new FileInputStream(xmlFile)));
            } catch (IOException e) {
                logger.error(e);
            }
            return Collections.EMPTY_SET;
        }
    }

    public void appendData(byte[] array) {
        Set<Person> catalog = getData();
        ApplicationContext context = ApplicationContextProvider.getApplicationContext();
        Unmarshaller unMarshaller = (Unmarshaller) context.getBean("xstreamMarshallerBean");
        Marshaller marshaller = (Marshaller) context.getBean("xstreamMarshallerBean");
        try {
            Set<Person> appender = (Set<Person>) unMarshaller.unmarshal(new StreamSource(new ByteArrayInputStream(array)));
            catalog.addAll(appender);

            synchronized (xmlFile) {
                marshaller.marshal(catalog, new StreamResult(new FileWriter(xmlFile)));
            }

        } catch (IOException e) {
            logger.error(e);
        }

    }
}
